package com.dongyimai.oauth.token;

import com.alibaba.fastjson.JSON;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.jwt.Jwt;
import org.springframework.security.jwt.JwtHelper;
import org.springframework.security.jwt.crypto.sign.RsaSigner;
import org.springframework.security.oauth2.provider.token.store.KeyStoreKeyFactory;

import java.security.KeyPair;
import java.security.PublicKey;
import java.security.interfaces.RSAPrivateCrtKey;
import java.util.HashMap;
import java.util.Map;

public class AdminToken {

    /**
     * 用于远程调用 user 模块中的 findByUsername
     * @return
     */
   public static String getAdminToken(){
       // 证书名
       String key_location = "dongyimai.jks";
       // 密钥库的访问密码
       String storePass = "dongyimai";
       // 密钥别名
       String alias = "dongyimai";
       // 密钥的访问密码
       String keyPass = "dongyimai";

       // 1. 通过证书名来获取resource对象：获取证书文件
       ClassPathResource resource = new ClassPathResource(key_location);

       // 2.构建秘钥库秘钥工厂(工厂模式): public KeyStoreKeyFactory(Resource resource, char[] password)
       // 利用resource对象,通过秘钥库的访问密码(storepass)来获取证书(秘钥库文件)中的内容
       KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(resource, storePass.toCharArray());

       // 3.获取秘钥对(公钥和秘钥):public KeyPair getKeyPair(String alias, char[] password):(秘钥别名,秘钥的访问密码)
       KeyPair keyPair = keyStoreKeyFactory.getKeyPair(alias, keyPass.toCharArray());

       // 4.获取公钥和秘钥(RSA:HASH算法:则PrivateKey的子类)
       PublicKey publicKey = keyPair.getPublic();  // 公钥
       RSAPrivateCrtKey privatetKey =(RSAPrivateCrtKey)keyPair.getPrivate();  // 私钥

       // 5.根据私钥来创建令牌
       Map<String,Object> map = new HashMap<String, Object>();
       map.put("username","admin");
       map.put("role","admin");
       // 采用"数字签名",生成token的摘要（digest）
       Jwt jwt = JwtHelper.encode(JSON.toJSONString(map), new RsaSigner(privatetKey));
       System.out.println(jwt);

       // 6.将令牌加密
       String token = jwt.getEncoded();
       return token;
   }
}
